<template>
  <view class="login-page">
    <view class="bg">
      <image src="../../static/login_bg.jpeg"></image>
    </view>

    <view class="wrapper">
      <view class="header">
        <view class="logo">
          <image src="/static/logo.svg" />
        </view>

        <text class="title">欢迎登录</text>
      </view>

      <uni-forms ref="form" class="form" :modelValue="formData" :rules="rules">
        <uni-forms-item name="phone_num" required>
          <uni-easyinput v-model="formData.phone_num" placeholder="请输入手机号" type="number" prefix-icon="phone" />
        </uni-forms-item>

        <uni-forms-item name="password" required>
          <uni-easyinput v-model="formData.password" placeholder="请输入密码" type="password" prefix-icon="locked" />
        </uni-forms-item>

        <view class="action-box">
          <button class="login-btn" @click="handleLogin">登录</button>
          <view class="register-link">
            没有账号？
            <text @click="navToRegister">立即注册</text>
          </view>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import aesEncrypt from '../../utils/encrypt'
export default {
  data() {
    return {
      formData: {
        phone_num: '',
        password: ''
      },
      aa: null,
      rules: {
        password: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '请输入密码'
            },
            // 对name字段进行长度验证
            {
              minLength: 8,
              maxLength: 16,
              errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '密码',
          validateTrigger: 'submit'
        },

        phone_num: {
          rules: [
            {
              required: true,
              errorMessage: '请输入手机号'
            },
            {
              format: 'number',
              errorMessage: '请输入合法的手机号'
            },
            {
              pattern: '^(?:\\+?86)?1(?:3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[134578]|8[0-9]|9[0-35-9])\\d{8}$',
              errorMessage: '请输入合法的手机号'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '手机号',
          validateTrigger: 'submit'
        }
      },
      smsCode: ''
    }
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate(async (valid) => {
        if (valid != null) {
          return
        }
        uni.showLoading({ title: '登录中...' })

        // 获取密钥，过期后重新拿
        if (this.aa == null || this.aa.et < new Date().getTime()) {
          const a = await uni.request({
            method: 'GET',
            url: this.$domain.data + '/userRegLogin'
          })

          if (a.data.status != 200) {
            this.$checkStatus(a.data.status)
            this.aa = null
            return
          }
          this.aa = JSON.parse(a.data.data)
          this.aa.id = this.getExId(a.data.data)
        }

        // 数据加密

        const formData = this.formData
        const pwd = aesEncrypt(formData.password, this.aa.a.s, this.aa.a.iv)
        const phone_num = formData.phone_num

        const { data: res } = await uni.request({
          url: `${this.$domain.data}/loginUser`,
          method: 'POST',
          data: {
            phone_num: phone_num,
            password: pwd,
            a_id: this.aa.id
          }
        })

        uni.hideLoading()

        if (res.status != 200) {
          this.$checkStatus(res.status, res.message)
          return
        }

        uni.showToast({
          icon: 'success',
          title: '登录成功'
        })

        getApp().globalData.userInfo = res.data.user
        getApp().globalData.header.Authorization = res.data.token

        // 删除签到缓存
        try {
          uni.removeStorageSync('signed')
        } catch {}

        // 保存token
        uni.setStorageSync('token', res.data.token)
        uni.setStorageSync('userInfo', JSON.stringify(res.data.user))

        // 调用登录接口
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/index/index' })
        }, 500)
      })
    },
    getExId(jsonStr) {
      const arr = jsonStr.split(',')
      const ids = arr[arr.length - 1]
      const id = ids.split('}')[0].split(':')[1] + ''

      return id
    },
    navToRegister() {
      uni.navigateTo({ url: '/pages/login/register' })
    }
  }
}
</script>

<style lang="scss">
.login-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .bg {
    z-index: -1;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100vw;
    height: 100vh;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .wrapper {
    width: 670upx;
    padding: 30upx 40upx;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 20upx;
    position: relative;
    box-sizing: border-box;
  }

  .header {
    text-align: center;
    margin-bottom: 50upx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .logo {
      width: 100upx;
      height: 100upx;
      //background-color: rgba(255, 255, 255, 0.9);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .title {
      font-size: 48upx;
      font-weight: bold;
      display: block;
    }
  }

  .login-btn {
    background: #007aff;
    color: #fff;
    height: 90upx;
    line-height: 90upx;
    border-radius: 45upx;
    font-size: 34upx;
    margin-top: 60upx;
  }

  .register-link {
    text-align: center;
    margin-top: 40upx;
    color: #666;

    text {
      color: #007aff;
      margin-left: 10upx;
    }
  }
}
</style>
